Data Scientist Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App

This notebook walks you through one of the most popular Udacity projects across machine learning and artificial intellegence nanodegree programs. The goal is to classify images of dogs according to their breed.

If you are looking for a more guided capstone project related to deep learning and convolutional neural networks, this might be just it. Notice that even if you follow the notebook to creating your classifier, you must still create a blog post or deploy an application to fulfill the requirements of the capstone project.

Also notice, you may be able to use only parts of this notebook (for example certain coding portions or the data) without completing all parts and still meet all requirements of the capstone project.


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob
import pandas as pd
import matplotlib.pyplot as plt

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('../../../data/dog_images/train')
valid_files, valid_targets = load_dataset('../../../data/dog_images/valid')
test_files, test_targets = load_dataset('../../../data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("../../../data/dog_images/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("../../../data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Data Exploration

Dogs dataset:

In [3]:
# making sure that we do not have any missing values
assert len(train_files)==len(train_targets)
assert len(valid_files)==len(valid_targets)
assert len(test_files)==len(test_targets)
In [4]:
def show_random_files(data, n):
    """Show random images from data files"""
    files = pd.Series(data).sample(n)
    
    for i in files.values:
        plt.imshow(plt.imread(i))
        plt.axis('off')
        plt.show()
In [5]:
train_files, "*" * 100 ,train_targets
Out[5]:
(array(['../../../data/dog_images/train/095.Kuvasz/Kuvasz_06442.jpg',
        '../../../data/dog_images/train/057.Dalmatian/Dalmatian_04054.jpg',
        '../../../data/dog_images/train/088.Irish_water_spaniel/Irish_water_spaniel_06014.jpg',
        ...,
        '../../../data/dog_images/train/029.Border_collie/Border_collie_02069.jpg',
        '../../../data/dog_images/train/046.Cavalier_king_charles_spaniel/Cavalier_king_charles_spaniel_03261.jpg',
        '../../../data/dog_images/train/048.Chihuahua/Chihuahua_03416.jpg'], 
       dtype='<U114'),
 '****************************************************************************************************',
 array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],
        ..., 
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ...,  0.,  0.,  0.],
        [ 0.,  0.,  0., ...,  0.,  0.,  0.]]))
In [6]:
# show random photos
show_random_files(train_files, 5)
In [7]:
show_random_files(valid_files, 5)
In [8]:
show_random_files(test_files, 5)

It sounds like the images are in a good condition and suitable for training. We do not have any missing values or abnormalities. However if we could obtain more labeled data it would be better

In [9]:
# explore the dogs breeds
dog_main_breeds = pd.Series(train_files).str.replace("_"," ")\
.str.split(".", expand=True)[7]\
.str.split("/", expand=True)[0].value_counts()
In [10]:
dog_main_breeds.describe()
Out[10]:
count    133.000000
mean      50.225564
std       11.863885
min       26.000000
25%       42.000000
50%       50.000000
75%       61.000000
max       77.000000
Name: 0, dtype: float64
  • There are 133 breeds in our dataset.
  • We have 50 images for breed on average.
  • The minimum number of images for a breed is 26 and the maximum is 77.
  • The big number of standrad deviation shows high variability in the number of images for each breed.
In [11]:
# get top dog breeds
dog_main_breeds[:10]
Out[11]:
Alaskan malamute                  77
Border collie                     74
Basset hound                      73
Dalmatian                         71
Bull terrier                      69
Basenji                           69
Bullmastiff                       69
Cavalier king charles spaniel     67
Australian shepherd               66
American staffordshire terrier    66
Name: 0, dtype: int64
In [12]:
# bar chart of the top 10 dog breeds
dog_main_breeds[:10].plot(kind='barh', color='green')
plt.xlabel("count of dogs' images in the breed")
plt.ylabel("dog breeds")
plt.title("Number of dogs' images per breed")
plt.show()
In [13]:
dog_main_breeds.hist()
plt.title("breeds files distribution")
plt.xlabel("number of files")
plt.ylabel("frequency")
Out[13]:
Text(0,0.5,'frequency')

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [14]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [15]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    """Detect a human face in an image"""
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

  • The percentage of files which are deteced as faces in humans files is 100.0%
  • The percentage of files which are deteced as faces in dogs files is 11.0%
In [16]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
humans_files = [face_detector(h_img) for h_img in human_files_short]
dogs_files = [face_detector(d_img) for d_img in dog_files_short]

# calculate the percentage
humans_files_percentage = np.mean(humans_files)*100
dogs_files_percentage = np.mean(dogs_files)*100

print(f"The percentage of files which are deteced as faces in humans files is {humans_files_percentage}%",
     f"\nThe percentage of files which are deteced as faces in dogs files is {dogs_files_percentage}%")
The percentage of files which are deteced as faces in humans files is 100.0% 
The percentage of files which are deteced as faces in dogs files is 11.0%

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: It is quite important to define a clear set of rules for the user in order to run our algorithm correctly. If we do not want to define any rules and let the user choose their image, we can solve this using multi-layer detection system starting from object detection, until we decide the image has humans or not. However, such a process will require a huge amount of images and a great computational power to generate such multi-model application. Therefore, we should define what the model expects from the user in clear words to avoid any problems that may hit the accuracy of our current model.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [17]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [18]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 2s 0us/step

Preprocessing steps:

After splitting the data into train, validation, test groups we need to convert them to the tensors type in order to be understood by TensorFlow.

Tensors explanation:

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [22]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [23]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [24]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

  • The percentage of files which are deteced as dogs in humans files is 0.0%
  • The percentage of files which are deteced as dogs in dogs files is 100.0%
In [25]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
humans_files = [dog_detector(h_img) for h_img in human_files_short]
dogs_files = [dog_detector(d_img) for d_img in dog_files_short]

# calculate the percentage
humans_files_percentage = np.mean(humans_files)*100
dogs_files_percentage = np.mean(dogs_files)*100

print(f"The percentage of files which are deteced as dogs in humans files is {humans_files_percentage}%",
     f"\nThe percentage of files which are deteced as dogs in dogs files is {dogs_files_percentage}%")
The percentage of files which are deteced as dogs in humans files is 0.0% 
The percentage of files which are deteced as dogs in dogs files is 100.0%

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [31]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:12<00:00, 92.57it/s] 
100%|██████████| 835/835 [00:09<00:00, 92.42it/s] 
100%|██████████| 836/836 [00:07<00:00, 104.81it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: In fact, I have used the hinted architectiure above. However, I added one more layer to increase the number of layers and the model complexity. The reason that CNN works well with image classification and specifically 2D convolutional layers that the 2D layers has two dimensions and the data that has two dimensions like images are well suited to this type of neural networks.

In [26]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.

# model architecture
model.add(Conv2D(input_shape=(224, 224, 3), filters=8, kernel_size=2, strides=1, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=16, kernel_size=2, strides=1, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=32, kernel_size=2, strides=1, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=64, kernel_size=2, strides=1, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(GlobalAveragePooling2D())
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 8)       104       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 112, 112, 8)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 112, 112, 16)      528       
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 56, 56, 16)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 56, 56, 32)        2080      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 28, 28, 32)        0         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 28, 28, 64)        8256      
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 14, 14, 64)        0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 64)                0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               8645      
=================================================================
Total params: 19,613
Trainable params: 19,613
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [29]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [32]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 10

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
6640/6680 [============================>.] - ETA: 0s - loss: 4.8842 - acc: 0.0083Epoch 00001: val_loss improved from inf to 4.86782, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 17s 3ms/step - loss: 4.8843 - acc: 0.0084 - val_loss: 4.8678 - val_acc: 0.0144
Epoch 2/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8612 - acc: 0.0128Epoch 00002: val_loss improved from 4.86782 to 4.85167, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 16s 2ms/step - loss: 4.8611 - acc: 0.0127 - val_loss: 4.8517 - val_acc: 0.0204
Epoch 3/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8391 - acc: 0.0140Epoch 00003: val_loss improved from 4.85167 to 4.82752, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 16s 2ms/step - loss: 4.8389 - acc: 0.0139 - val_loss: 4.8275 - val_acc: 0.0204
Epoch 4/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8101 - acc: 0.0164Epoch 00004: val_loss improved from 4.82752 to 4.79984, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 16s 2ms/step - loss: 4.8102 - acc: 0.0165 - val_loss: 4.7998 - val_acc: 0.0216
Epoch 5/10
6640/6680 [============================>.] - ETA: 0s - loss: 4.7763 - acc: 0.0227Epoch 00005: val_loss improved from 4.79984 to 4.77413, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 16s 2ms/step - loss: 4.7769 - acc: 0.0229 - val_loss: 4.7741 - val_acc: 0.0180
Epoch 6/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7436 - acc: 0.0248Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 16s 2ms/step - loss: 4.7439 - acc: 0.0247 - val_loss: 4.7842 - val_acc: 0.0144
Epoch 7/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7084 - acc: 0.0272Epoch 00007: val_loss improved from 4.77413 to 4.71714, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 16s 2ms/step - loss: 4.7083 - acc: 0.0271 - val_loss: 4.7171 - val_acc: 0.0251
Epoch 8/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6727 - acc: 0.0285Epoch 00008: val_loss improved from 4.71714 to 4.68517, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 16s 2ms/step - loss: 4.6727 - acc: 0.0286 - val_loss: 4.6852 - val_acc: 0.0263
Epoch 9/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6339 - acc: 0.0300Epoch 00009: val_loss improved from 4.68517 to 4.65843, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 16s 2ms/step - loss: 4.6339 - acc: 0.0299 - val_loss: 4.6584 - val_acc: 0.0335
Epoch 10/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6000 - acc: 0.0347Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 16s 2ms/step - loss: 4.5995 - acc: 0.0350 - val_loss: 4.7116 - val_acc: 0.0359
Out[32]:
<keras.callbacks.History at 0x7f95c9f10320>

Load the Model with the Best Validation Loss

In [19]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [33]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 3.4689%

I used the hinted model to create the above-mentioned model but the results are too low. However, I added more layers in order to improve the results and it actually improved after testing it and realized that I need to add more and more layers. This has led me to test the following model which I believe is built on a lot of layers and enormous amount of parameters.


Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [34]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [35]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [36]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [37]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6560/6680 [============================>.] - ETA: 0s - loss: 12.4501 - acc: 0.1133Epoch 00001: val_loss improved from inf to 10.80645, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 292us/step - loss: 12.4329 - acc: 0.1138 - val_loss: 10.8065 - val_acc: 0.1976
Epoch 2/20
6520/6680 [============================>.] - ETA: 0s - loss: 10.0656 - acc: 0.2696Epoch 00002: val_loss improved from 10.80645 to 9.99809, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 10.0646 - acc: 0.2699 - val_loss: 9.9981 - val_acc: 0.2850
Epoch 3/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.3513 - acc: 0.3414Epoch 00003: val_loss improved from 9.99809 to 9.35292, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 260us/step - loss: 9.3403 - acc: 0.3418 - val_loss: 9.3529 - val_acc: 0.3353
Epoch 4/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.9634 - acc: 0.3880Epoch 00004: val_loss improved from 9.35292 to 9.33429, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 264us/step - loss: 8.9610 - acc: 0.3883 - val_loss: 9.3343 - val_acc: 0.3449
Epoch 5/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.8004 - acc: 0.4154Epoch 00005: val_loss improved from 9.33429 to 9.14302, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 263us/step - loss: 8.7813 - acc: 0.4160 - val_loss: 9.1430 - val_acc: 0.3641
Epoch 6/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.5474 - acc: 0.4318Epoch 00006: val_loss improved from 9.14302 to 8.97022, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 8.5216 - acc: 0.4334 - val_loss: 8.9702 - val_acc: 0.3737
Epoch 7/20
6500/6680 [============================>.] - ETA: 0s - loss: 8.4141 - acc: 0.4515Epoch 00007: val_loss improved from 8.97022 to 8.93088, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 252us/step - loss: 8.3986 - acc: 0.4527 - val_loss: 8.9309 - val_acc: 0.3832
Epoch 8/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.3247 - acc: 0.4595Epoch 00008: val_loss improved from 8.93088 to 8.80993, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 8.3123 - acc: 0.4603 - val_loss: 8.8099 - val_acc: 0.3749
Epoch 9/20
6500/6680 [============================>.] - ETA: 0s - loss: 8.0821 - acc: 0.4692Epoch 00009: val_loss improved from 8.80993 to 8.73129, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 8.0881 - acc: 0.4690 - val_loss: 8.7313 - val_acc: 0.3928
Epoch 10/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.8822 - acc: 0.4818Epoch 00010: val_loss improved from 8.73129 to 8.49612, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 7.9013 - acc: 0.4814 - val_loss: 8.4961 - val_acc: 0.4048
Epoch 11/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.7903 - acc: 0.4994Epoch 00011: val_loss improved from 8.49612 to 8.47870, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 249us/step - loss: 7.7967 - acc: 0.4987 - val_loss: 8.4787 - val_acc: 0.4120
Epoch 12/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.7648 - acc: 0.5032Epoch 00012: val_loss improved from 8.47870 to 8.43498, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 7.7442 - acc: 0.5039 - val_loss: 8.4350 - val_acc: 0.4084
Epoch 13/20
6520/6680 [============================>.] - ETA: 0s - loss: 7.5355 - acc: 0.5104Epoch 00013: val_loss improved from 8.43498 to 8.10576, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 252us/step - loss: 7.5233 - acc: 0.5106 - val_loss: 8.1058 - val_acc: 0.4299
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.3532 - acc: 0.5285Epoch 00014: val_loss improved from 8.10576 to 8.05817, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 248us/step - loss: 7.3456 - acc: 0.5290 - val_loss: 8.0582 - val_acc: 0.4311
Epoch 15/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.2861 - acc: 0.5341Epoch 00015: val_loss improved from 8.05817 to 7.97619, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 7.2890 - acc: 0.5338 - val_loss: 7.9762 - val_acc: 0.4323
Epoch 16/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.2076 - acc: 0.5385Epoch 00016: val_loss improved from 7.97619 to 7.91940, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 7.1907 - acc: 0.5394 - val_loss: 7.9194 - val_acc: 0.4515
Epoch 17/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.1596 - acc: 0.5457Epoch 00017: val_loss improved from 7.91940 to 7.78091, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 7.1303 - acc: 0.5476 - val_loss: 7.7809 - val_acc: 0.4611
Epoch 18/20
6540/6680 [============================>.] - ETA: 0s - loss: 7.1124 - acc: 0.5495Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 249us/step - loss: 7.0977 - acc: 0.5503 - val_loss: 7.8013 - val_acc: 0.4443
Epoch 19/20
6600/6680 [============================>.] - ETA: 0s - loss: 6.9013 - acc: 0.5562Epoch 00019: val_loss improved from 7.78091 to 7.61563, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 6.9095 - acc: 0.5558 - val_loss: 7.6156 - val_acc: 0.4647
Epoch 20/20
6540/6680 [============================>.] - ETA: 0s - loss: 6.8029 - acc: 0.5665Epoch 00020: val_loss improved from 7.61563 to 7.56359, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 6.8078 - acc: 0.5663 - val_loss: 7.5636 - val_acc: 0.4659
Out[37]:
<keras.callbacks.History at 0x7f95c90739e8>

Load the Model with the Best Validation Loss

In [38]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [39]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 44.9761%

Using the previous model VGG16, we notice that there is a daramtic increase in accuracy that outsmart our previous raw CNN model. However, using the transfer learning with bigger model like VGG19 may increase the accuracy.

Predict Dog Breed with the Model

In [41]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [42]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
import urllib.request
import os.path as flib


url = 'https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/DogVGG19Data.npz'

# download the model if it does not exist
if flib.exists('bottleneck_features/DogVGG19Data.npz')==False:
    print("Downloading the model...")
    urllib.request.urlretrieve(url, 'bottleneck_features/DogVGG19Data.npz')
    print("Model downloaded successfully")

# create the model bottleneck
bottleneck_features = np.load('bottleneck_features/DogVGG19Data.npz')
train_VGG19 = bottleneck_features['train']
valid_VGG19 = bottleneck_features['valid']
test_VGG19 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: Because I noticed that VGG16 result is better than the raw CNN model, so I decided to use transfer learning with VGG19 and add some additional layers on top of it in order to increase the accuracy and to allow the network to adapt more with my current dataset.

In [52]:
### TODO: Define your architecture.

# VGG19 model architecture
VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_model.add(Dense(360, activation='relu'))
VGG19_model.add(Dropout(0.2))
VGG19_model.add(Dense(240, activation='relu'))
VGG19_model.add(Dropout(0.2))
VGG19_model.add(Dense(133, activation='softmax'))

VGG19_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_4 ( (None, 512)               0         
_________________________________________________________________
dense_6 (Dense)              (None, 360)               184680    
_________________________________________________________________
dropout_3 (Dropout)          (None, 360)               0         
_________________________________________________________________
dense_7 (Dense)              (None, 240)               86640     
_________________________________________________________________
dropout_4 (Dropout)          (None, 240)               0         
_________________________________________________________________
dense_8 (Dense)              (None, 133)               32053     
=================================================================
Total params: 303,373
Trainable params: 303,373
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [53]:
### TODO: Compile the model.
VGG19_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [54]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', 
                               verbose=1, save_best_only=True)

VGG19_model.fit(train_VGG19, train_targets, 
          validation_data=(valid_VGG19, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/50
6640/6680 [============================>.] - ETA: 0s - loss: 3.4671 - acc: 0.2819Epoch 00001: val_loss improved from inf to 1.53105, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 3s 448us/step - loss: 3.4566 - acc: 0.2835 - val_loss: 1.5310 - val_acc: 0.5749
Epoch 2/50
6520/6680 [============================>.] - ETA: 0s - loss: 1.5285 - acc: 0.5850Epoch 00002: val_loss improved from 1.53105 to 1.15566, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 340us/step - loss: 1.5265 - acc: 0.5856 - val_loss: 1.1557 - val_acc: 0.6419
Epoch 3/50
6580/6680 [============================>.] - ETA: 0s - loss: 1.1782 - acc: 0.6769Epoch 00003: val_loss improved from 1.15566 to 1.02440, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 340us/step - loss: 1.1825 - acc: 0.6762 - val_loss: 1.0244 - val_acc: 0.7042
Epoch 4/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.9648 - acc: 0.7276Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.9682 - acc: 0.7274 - val_loss: 1.1981 - val_acc: 0.6743
Epoch 5/50
6500/6680 [============================>.] - ETA: 0s - loss: 0.8881 - acc: 0.7569Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 334us/step - loss: 0.8888 - acc: 0.7566 - val_loss: 1.0336 - val_acc: 0.7174
Epoch 6/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.8418 - acc: 0.7784Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s 332us/step - loss: 0.8416 - acc: 0.7789 - val_loss: 1.1247 - val_acc: 0.7210
Epoch 7/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.7481 - acc: 0.8005Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.7460 - acc: 0.8010 - val_loss: 1.1820 - val_acc: 0.7246
Epoch 8/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.6901 - acc: 0.8148Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 335us/step - loss: 0.6888 - acc: 0.8148 - val_loss: 1.2250 - val_acc: 0.7150
Epoch 9/50
6540/6680 [============================>.] - ETA: 0s - loss: 0.6694 - acc: 0.8246Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 346us/step - loss: 0.6666 - acc: 0.8257 - val_loss: 1.2516 - val_acc: 0.7413
Epoch 10/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.6281 - acc: 0.8348Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 351us/step - loss: 0.6311 - acc: 0.8347 - val_loss: 1.2039 - val_acc: 0.7545
Epoch 11/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.6234 - acc: 0.8442Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 355us/step - loss: 0.6255 - acc: 0.8437 - val_loss: 1.1526 - val_acc: 0.7545
Epoch 12/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.5918 - acc: 0.8574Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 352us/step - loss: 0.5902 - acc: 0.8579 - val_loss: 1.2730 - val_acc: 0.7581
Epoch 13/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.5554 - acc: 0.8664Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 349us/step - loss: 0.5546 - acc: 0.8665 - val_loss: 1.6097 - val_acc: 0.7521
Epoch 14/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.5848 - acc: 0.8620Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 346us/step - loss: 0.5865 - acc: 0.8618 - val_loss: 1.4117 - val_acc: 0.7605
Epoch 15/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.5273 - acc: 0.8774Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 337us/step - loss: 0.5271 - acc: 0.8774 - val_loss: 1.4515 - val_acc: 0.7509
Epoch 16/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.5592 - acc: 0.8764Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 337us/step - loss: 0.5608 - acc: 0.8760 - val_loss: 1.3044 - val_acc: 0.7545
Epoch 17/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.5504 - acc: 0.8776Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.5505 - acc: 0.8777 - val_loss: 1.5160 - val_acc: 0.7569
Epoch 18/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.5507 - acc: 0.8879Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 338us/step - loss: 0.5511 - acc: 0.8880 - val_loss: 1.6997 - val_acc: 0.7341
Epoch 19/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.5512 - acc: 0.8813Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.5492 - acc: 0.8816 - val_loss: 1.6919 - val_acc: 0.7653
Epoch 20/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.5418 - acc: 0.8901Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 338us/step - loss: 0.5425 - acc: 0.8900 - val_loss: 1.6417 - val_acc: 0.7473
Epoch 21/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.4974 - acc: 0.8977Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.4990 - acc: 0.8970 - val_loss: 1.6645 - val_acc: 0.7605
Epoch 22/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.5066 - acc: 0.8983Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 2s 339us/step - loss: 0.5056 - acc: 0.8990 - val_loss: 1.6505 - val_acc: 0.7665
Epoch 23/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.5077 - acc: 0.9011Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.5067 - acc: 0.9013 - val_loss: 1.7158 - val_acc: 0.7581
Epoch 24/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.5134 - acc: 0.9053Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 2s 334us/step - loss: 0.5140 - acc: 0.9054 - val_loss: 1.8161 - val_acc: 0.7677
Epoch 25/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.5256 - acc: 0.9026Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 2s 334us/step - loss: 0.5257 - acc: 0.9031 - val_loss: 1.9812 - val_acc: 0.7533
Epoch 26/50
6540/6680 [============================>.] - ETA: 0s - loss: 0.5788 - acc: 0.9009Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 2s 333us/step - loss: 0.5785 - acc: 0.9013 - val_loss: 2.1063 - val_acc: 0.7557
Epoch 27/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.5321 - acc: 0.9062Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 2s 335us/step - loss: 0.5315 - acc: 0.9061 - val_loss: 2.2550 - val_acc: 0.7377
Epoch 28/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.5115 - acc: 0.9123Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 2s 335us/step - loss: 0.5135 - acc: 0.9120 - val_loss: 2.1267 - val_acc: 0.7437
Epoch 29/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.5122 - acc: 0.9138Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 2s 331us/step - loss: 0.5127 - acc: 0.9138 - val_loss: 1.9652 - val_acc: 0.7545
Epoch 30/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.5975 - acc: 0.9032Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 2s 332us/step - loss: 0.6008 - acc: 0.9027 - val_loss: 2.2495 - val_acc: 0.7581
Epoch 31/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.5511 - acc: 0.9128Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 2s 337us/step - loss: 0.5521 - acc: 0.9127 - val_loss: 2.3244 - val_acc: 0.7677
Epoch 32/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.6137 - acc: 0.9097Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 2s 336us/step - loss: 0.6091 - acc: 0.9102 - val_loss: 2.2678 - val_acc: 0.7605
Epoch 33/50
6540/6680 [============================>.] - ETA: 0s - loss: 0.5395 - acc: 0.9142Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 2s 335us/step - loss: 0.5516 - acc: 0.9135 - val_loss: 2.1895 - val_acc: 0.7677
Epoch 34/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.5209 - acc: 0.9173Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 2s 337us/step - loss: 0.5136 - acc: 0.9184 - val_loss: 2.2208 - val_acc: 0.7749
Epoch 35/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.4915 - acc: 0.9270Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 2s 337us/step - loss: 0.4910 - acc: 0.9269 - val_loss: 2.6027 - val_acc: 0.7317
Epoch 36/50
6520/6680 [============================>.] - ETA: 0s - loss: 0.5284 - acc: 0.9150Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 2s 337us/step - loss: 0.5362 - acc: 0.9151 - val_loss: 2.3941 - val_acc: 0.7641
Epoch 37/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.6011 - acc: 0.9120Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 2s 340us/step - loss: 0.5994 - acc: 0.9120 - val_loss: 2.4076 - val_acc: 0.7653
Epoch 38/50
6540/6680 [============================>.] - ETA: 0s - loss: 0.5630 - acc: 0.9202Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 2s 337us/step - loss: 0.5645 - acc: 0.9204 - val_loss: 2.3556 - val_acc: 0.7725
Epoch 39/50
6560/6680 [============================>.] - ETA: 0s - loss: 0.5483 - acc: 0.9174Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 2s 334us/step - loss: 0.5549 - acc: 0.9172 - val_loss: 2.4028 - val_acc: 0.7581
Epoch 40/50
6620/6680 [============================>.] - ETA: 0s - loss: 0.5273 - acc: 0.9225Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 2s 335us/step - loss: 0.5237 - acc: 0.9226 - val_loss: 2.5264 - val_acc: 0.7545
Epoch 41/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.5591 - acc: 0.9238Epoch 00041: val_loss did not improve
6680/6680 [==============================] - 2s 341us/step - loss: 0.5584 - acc: 0.9238 - val_loss: 2.4513 - val_acc: 0.7593
Epoch 42/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.5847 - acc: 0.9191Epoch 00042: val_loss did not improve
6680/6680 [==============================] - 2s 334us/step - loss: 0.5829 - acc: 0.9193 - val_loss: 2.6115 - val_acc: 0.7533
Epoch 43/50
6640/6680 [============================>.] - ETA: 0s - loss: 0.6029 - acc: 0.9196Epoch 00043: val_loss did not improve
6680/6680 [==============================] - 2s 340us/step - loss: 0.6022 - acc: 0.9198 - val_loss: 2.4273 - val_acc: 0.7677
Epoch 44/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.5535 - acc: 0.9248Epoch 00044: val_loss did not improve
6680/6680 [==============================] - 2s 346us/step - loss: 0.5572 - acc: 0.9238 - val_loss: 2.5883 - val_acc: 0.7677
Epoch 45/50
6660/6680 [============================>.] - ETA: 0s - loss: 0.6109 - acc: 0.9225Epoch 00045: val_loss did not improve
6680/6680 [==============================] - 2s 343us/step - loss: 0.6096 - acc: 0.9226 - val_loss: 2.6903 - val_acc: 0.7653
Epoch 46/50
6540/6680 [============================>.] - ETA: 0s - loss: 0.5835 - acc: 0.9237Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 2s 340us/step - loss: 0.5853 - acc: 0.9238 - val_loss: 2.7765 - val_acc: 0.7425
Epoch 47/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.6038 - acc: 0.9269Epoch 00047: val_loss did not improve
6680/6680 [==============================] - 2s 340us/step - loss: 0.6022 - acc: 0.9268 - val_loss: 2.6424 - val_acc: 0.7641
Epoch 48/50
6580/6680 [============================>.] - ETA: 0s - loss: 0.5882 - acc: 0.9255Epoch 00048: val_loss did not improve
6680/6680 [==============================] - 2s 342us/step - loss: 0.5913 - acc: 0.9253 - val_loss: 2.7361 - val_acc: 0.7473
Epoch 49/50
6540/6680 [============================>.] - ETA: 0s - loss: 0.5732 - acc: 0.9272Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 2s 342us/step - loss: 0.5732 - acc: 0.9271 - val_loss: 2.5322 - val_acc: 0.7545
Epoch 50/50
6600/6680 [============================>.] - ETA: 0s - loss: 0.5518 - acc: 0.9271Epoch 00050: val_loss did not improve
6680/6680 [==============================] - 2s 340us/step - loss: 0.5540 - acc: 0.9271 - val_loss: 2.5286 - val_acc: 0.7617
Out[54]:
<keras.callbacks.History at 0x7f95abf0fbe0>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [55]:
### TODO: Load the model weights with the best validation loss.
VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [56]:
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG19_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 70.0957%

After testing VGG19 it is obvious that the accuracy has increased and surpassed VGG16 model. Therefore, We will use VGG19 as base to build our final model on it.

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [48]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
def VGG19_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG19(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG19_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

A sample image and output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

This photo looks like an Afghan Hound.

(IMPLEMENTATION) Write your Algorithm

In [49]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def predict_image(image_path):
    """Predict the image of the human/dog and its breed"""
    import matplotlib.pyplot as plt
    # print the image in the result
    plt.imshow(plt.imread(image_path))
    plt.axis('off')
    plt.show()
    
    # get the breed
    breed = VGG19_predict_breed(image_path).split(".")[1].replace("_"," ")
    
    # check if it is human or dog or something else
    if face_detector(image_path):
        print("This picture is expected to have a human face and the resembling dog breed is", breed)
        return breed
    elif dog_detector(image_path):
        print("This picture is expected to have a dog from the", breed, "breed")
        return breed
    else:
        print("The picture may not include humans or dogs")
        return "Unknown"

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: I have tested the model with a lot of pictures. In most of the cases the model performed well. However, some cases it performed badly. It did not recognize the dog if the picture quality is not good.

There are many way to increase the accuracy of our model:

  • Model fine tuning (layers and parameters).
  • Try different models such resnet, inception, xception and so on.
  • Increase the number of training images and increase their variability in terms of quality.
  • Increase the number of epochs (it will require more time until the model becomes ready.
In [50]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
my_images = glob("images/*.*")
for i in my_images:
    predict_image(i)
    print("="*50)
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5
80142336/80134624 [==============================] - 1s 0us/step
This picture is expected to have a human face and the resembling dog breed is Bearded collie
==================================================
This picture is expected to have a dog from the Irish red and white setter breed
==================================================
This picture is expected to have a dog from the Brittany breed
==================================================
This picture is expected to have a dog from the Flat-coated retriever breed
==================================================
This picture is expected to have a dog from the Curly-coated retriever breed
==================================================
The picture may not include humans or dogs
==================================================
This picture is expected to have a dog from the Labrador retriever breed
==================================================
This picture is expected to have a dog from the Labrador retriever breed
==================================================
The picture may not include humans or dogs
==================================================
This picture is expected to have a human face and the resembling dog breed is American foxhound
==================================================
This picture is expected to have a dog from the Flat-coated retriever breed
==================================================
In [51]:
my_images = glob("my_images/*.*")
for i in my_images:
    predict_image(i)
    print("="*50)
This picture is expected to have a human face and the resembling dog breed is Basenji
==================================================
The picture may not include humans or dogs
==================================================
The picture may not include humans or dogs
==================================================
The picture may not include humans or dogs
==================================================
This picture is expected to have a dog from the Havanese breed
==================================================
In [ ]: